package org.xxmi.cors.configurations;


import java.util.Map;

import org.springframework.context.annotation.Configuration;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.util.StringUtils;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.server.HandshakeInterceptor;


@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
    /**
     * 配置信息代理
     */
    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        // 订阅Broker名称
        //用户订阅主题的前缀
        //  /topic 代表发布广播，即群发
        //  /queue 代表点对点，即发指定用户
        config.enableSimpleBroker("/queue", "/topic");
        // 全局使用的消息前缀（客户端订阅路径上会体现出来）
        config.setApplicationDestinationPrefixes("/webSocket");
        // 点对点使用的订阅前缀（客户端订阅路径上会体现出来），不设置的话，默认也是/user/
        // registry.setUserDestinationPrefix("/user/");
    }

    /**
     * 注册stomp的端点
     */
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        // 允许使用socketJs方式访问，访问点为webSocket，允许跨域
        // 在网页上我们就可以通过这个链接
        // http://localhost:{port}/{contentPath}/webSocket来和服务器的WebSocket连接


        // uni-app 必须用这种 （https://blog.csdn.net/slt6366078/article/details/80360941）
        registry.addEndpoint("/my-socket").setAllowedOrigins("*");

        registry.addEndpoint("/socket").setAllowedOrigins("*").withSockJS();
        registry.addEndpoint("/webSocket").setAllowedOrigins("*").withSockJS()
                //当服务器没有发送任何消息时以毫秒为单位的时间量，之后服务器应该向客户端发送心跳帧，以便防止连接中断。
                .setHeartbeatTime(10000)
                .setInterceptors(new HandshakeInterceptor() {
                    @Override
                    public boolean beforeHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Map<String, Object> map) throws Exception {
                        ServletServerHttpRequest req = (ServletServerHttpRequest) serverHttpRequest;
                        //获取token认证
                        String token = req.getServletRequest().getParameter("token");
                        System.out.println("token,==============" + token);
                        if (!StringUtils.isEmpty(token)) {
                            return true;
                        }
                        return false;
                    }

                    @Override
                    public void afterHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Exception e) {

                    }
                });
    }

}